Matrix addition involves adding two matrices of the same dimensions. For matrix addition to be valid, both matrices must have the same number of rows and columns. The addition of matrices is performed by adding the corresponding elements of each matrix and storing the result in a new matrix.
In C, matrices are typically represented as two-dimensional arrays. To perform matrix addition, can use nested loops to iterate over each element of the matrices and add the corresponding elements.
#include <stdio.h>
// Function to perform matrix addition
void matrixAddition(int rows, int columns, int matrix1[][3], int matrix2[][3], int result[][3]) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
result[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
}
int main() {
int rows = 3;
int columns = 3;
// Two matrices to be added
int matrix1[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int matrix2[3][3] = {
{9, 8, 7},
{6, 5, 4},
{3, 2, 1}
};
// Matrix to store the result
int result[3][3];
// Perform matrix addition
matrixAddition(rows, columns, matrix1, matrix2, result);
// Print the original matrices
printf("Matrix 1:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
printf("%d ", matrix1[i][j]);
}
printf("\n");
}
printf("\nMatrix 2:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
printf("%d ", matrix2[i][j]);
}
printf("\n");
}
// Print the result of matrix addition
printf("\nMatrix Addition Result:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}
return 0;
}
Matrix 1:
1 2 3
4 5 6
7 8 9
Matrix 2:
9 8 7
6 5 4
3 2 1
Matrix Addition Result:
10 10 10
10 10 10
10 10 10
What operation combines two matrices in C?
What is the result of adding two matrices of the same dimensions?
In matrix addition, what must be true about the dimensions of the matrices being added?